package com.itheima.service.mongo.impl;

import com.itheima.domain.mongo.MyVoice;
import com.itheima.domain.mongo.Voice;
import com.itheima.service.mongo.VoiceService;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@DubboService
public class VoiceServiceImpl implements VoiceService {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Override
    public void saveVoice(String soundUrl, Long userId) {

        Voice voice = new Voice();
        voice.setId(new ObjectId());//主键id
        voice.setSoundUrl(soundUrl);//语音地址
        voice.setUserId(userId);//发送者id
        voice.setCreated(System.currentTimeMillis());//发送时间

        //保存
        mongoTemplate.save(voice);

        //封装myVoice
        MyVoice myVoice = new MyVoice();
        myVoice.setId(new ObjectId());
        myVoice.setPublishId(voice.getId());
        myVoice.setCreated(voice.getCreated());
        mongoTemplate.save(myVoice,"MyVoice_"+userId);
    }

    //查询语音
    @Override
    public Voice findVoiceByCreated(Integer pageNum) {
        //创建查询条件
        Query qw = new Query(Criteria.where("state").is(0))
                .with(Sort.by(Sort.Order.asc("created")))
                .skip(pageNum).limit(1);

        Voice voice = mongoTemplate.findOne(qw, Voice.class);
        return voice;
    }

    //删除语音
    @Override
    public void removeVoice(Voice voice) {

        mongoTemplate.remove(voice);
    }

    //修改拾取状态
    @Override
    public void updateVoice(Voice voice) {
        voice.setState(1);
        mongoTemplate.save(voice);
        //同时修改个人语音表被拾取
        Query qw = new Query(Criteria.where("publishId").is(voice.getId()));
        Update update = new Update();
        update.set("state",1);
        mongoTemplate.updateFirst(qw,update,"MyVoice_" + voice.getUserId());
    }


}
